<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\News as NewsModel;
use app\common\controller\Backend;
use think\Request;

class News extends Backend
{
    //新闻列表
    public function index()
    {
        $newsList = NewsModel::select();
        return $this->fetch('news/index', ['newsList' => $newsList]);
    }

    //新闻编辑
    public function edit(Request $request)
    {
        $news = NewsModel::findOrEmpty($request->get('id', 0));
        return $this->fetch('news/edit', [
            'news' => $news
        ]);
    }

    //新闻保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();
            if (!empty($data['image-data'])) {
                $data['image'] = $this->uploadImageData($data['image-data']);
                unset($data['image-data']);
            }

            if (empty($data['id'])) {
                NewsModel::create($data);
            } else {
                NewsModel::update($data);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }

    //新闻删除
    public function delete(Request $request)
    {
        try {
            NewsModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}
